<?php
namespace EasyPhpWeb;

use Exception;
use Reflection;
use ReflectionClass;

class Route{
    public static $routeGet = [];
    private static $routePost = [];

    
    public static function get($uri, $action){
        self::$routeGet[$uri] = [
            'uri' => $uri,
            'action' => $action
        ];
    }

    public static function post($uri, $action){
        self::$routePost[$uri] = [
            'uri' => $uri,
            'action' => $action
        ];
    }

    /**
     * 执行
     */
    public static function do($method, $uri, $request, $response){
        $routeList = [];
        switch($method){
            case "GET" :
                $routeList = self::$routeGet;
                break;
            case "POST": 
                $routeList = self::$routePost;
                break;
        };

        if(!isset($routeList[$uri]) || empty($routeList[$uri])){
            throw new Exception("not fond url", 404);
        }
        $route = $routeList[$uri];

        list ($controllerStr, $actionStr) = explode("@", $route['action']);

        $class = new ReflectionClass("\\App\\Controller\\". $controllerStr);

        //创建控制器，并注入request 和 response
        $controller = $class->newInstanceArgs([$request, $response]);

        $action = $class->getMethod($actionStr);

        //执行操作
        return $action->invoke($controller);
    }
}